package com.cade.agriculturemall.view.shoppingCar.settlement;

import android.text.TextUtils;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BasePresenter;
import com.cade.agriculturemall.bean.NodeModel;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.model.Ticket;
import com.cade.agriculturemall.model.UserInfoEntity;
import com.cade.agriculturemall.utils.ConverUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Lobby on 2017/12/25.
 */

public class SettlementPresenter extends BasePresenter<SettlementContract.IView> implements SettlementContract.IPresenter {
    public SettlementPresenter(SettlementContract.IView view) {
        super(view);
    }

    private String type = "";
    private HashMap<String, NodeModel> hashMap;
    public String userId = "";
    private OrderEntity orderEntity = new OrderEntity();
    private ArrayList<String> orderObjectList = new ArrayList<>();

    public String getUserId() {
        return userId;
    }

    @Override
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void getFirstAddress() {
        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
        UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
        userId = user.getObjectId();
        AVQuery<AddressEntity> addressEntityAVQuery = new AVQuery<>("user_address");
        addressEntityAVQuery.whereEqualTo("ownerObjectId", user);
        addressEntityAVQuery.findInBackground(new FindCallback<AddressEntity>() {
            @Override
            public void done(List<AddressEntity> list, AVException e) {
                if (e == null) {
                    mView.getList(list);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    public ArrayList getOrderObjList() {
        return orderObjectList;
    }


    @Override
    public void getRefreshAddress(String objectId) {
        AVQuery<AddressEntity> addressEntityAVQuery = new AVQuery<>("user_address");
        addressEntityAVQuery.whereEqualTo("objectId", objectId);
        addressEntityAVQuery.findInBackground(new FindCallback<AddressEntity>() {
            @Override
            public void done(List<AddressEntity> list, AVException e) {
                if (e == null) {
                    if (list.size() != 0)
                        mView.getList(list);
                }
            }
        });
    }


    //                              订单号\订单金额\用户Id\下单时间\商品项\支付渠道\备注\地址编号


    @Override
    public void creatInOrder(final String dealNo, OrderEntity entity, HashMap<String, NodeModel> hashMap) {        //添加进订单表
        if (entity != null) {
            if (hashMap != null) {
                mView.showProgress();
                this.hashMap = hashMap;
                for (String shoper : hashMap.keySet()) {
                    entity.setOrderId(ConverUtil.getRandomNo());
                    final List<ShoppingCarsEntity> shoppingCarsEntity = hashMap.get(shoper).getShoppingCarsEntities();
                    final AVObject orderAvobject = new AVObject("order");
                    String remark = hashMap.get(shoper).getRemark();
                    Float orderPrice = 0f;
                    int goodsNum = 0;
                    for (ShoppingCarsEntity shoppingCarsEntity1 : shoppingCarsEntity) {
                        goodsNum += shoppingCarsEntity1.getQuantitate();
                        if (TextUtils.isEmpty(type)) {
                            orderPrice += shoppingCarsEntity1.getQuantitate() * Float.parseFloat(shoppingCarsEntity1.getPrice());
                        } else {
                            orderPrice = Float.parseFloat(shoppingCarsEntity1.getProId().getPriceNew());
                        }
                    }
                    orderAvobject.put("deal_no", dealNo);
                    orderAvobject.put("order_no", entity.getOrderId());
                    orderAvobject.put("order_amount_total", entity.getOrderPrice());
                    orderAvobject.put("user_Id", entity.getUserId());
                    orderAvobject.put("order_setttlement_time", entity.getOrderSetttlementTime());
                    orderAvobject.put("orderPriceCount", orderPrice + "");
                    orderAvobject.put("goods_count", goodsNum + "");
                    orderAvobject.put("order_count", entity.getProNum());
                    orderAvobject.put("payway", entity.getPayWay());
                    orderAvobject.put("tick_Id", entity.getTicketId());
                    if (TextUtils.isEmpty(entity.getOrderPayMoney())) {
                        orderAvobject.put("order_pay_money", entity.getOrderPriceCount());
                    } else {
                        orderAvobject.put("order_pay_money", entity.getOrderPayMoney());
                    }
                    if (remark == null) {
                        orderAvobject.put("remark", "");
                    } else {
                        orderAvobject.put("remark", remark);
                    }
                    orderAvobject.put("addressId", entity.getAddressId());
                    orderAvobject.put("order_status", entity.getOrderStatus());
                    orderAvobject.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e == null) {// 存储成功
                                if (TextUtils.isEmpty(type)) {
                                    getOrderEntity(dealNo, orderAvobject.getObjectId(), shoppingCarsEntity);
                                } else {
                                    addToCar(dealNo, orderAvobject.getObjectId(), shoppingCarsEntity);
                                }
                                orderObjectList.add(orderAvobject.getObjectId());// 保存成功之后，objectId 会自动从服务端加载到本地
                            } else {
                                // 失败的话，请检查网络环境以及 SDK 配置是否正确
                                mView.showError(e.getMessage());
                            }
                            mView.dismissProgress();
                        }
                    });
                }
            }
        }
    }

    /**
     * 商品详情跳转
     */
    private GoodsDetailEntity entity = new GoodsDetailEntity();

    public void setEntity(GoodsDetailEntity entity) {
        this.entity = entity;
    }

    public void addToCar(final String dealNo, final String orderId, final List<ShoppingCarsEntity> shoppingCarsEntity) {
        String currentUserId = user.getObjectId();
        final AVObject shoppingCars = new AVObject("ShoppingCars");
        shoppingCars.put("user_Id", currentUserId);
        shoppingCars.put("pro", entity);
        shoppingCars.put("quantitate", 1);
        shoppingCars.put("pro_price", entity.getPriceNew());
        shoppingCars.put("orderId", orderEntity);
        shoppingCars.put("dealOrderId", orderEntity.getOrderId());
        shoppingCars.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    getOrderEntity(dealNo, orderId, shoppingCarsEntity);
                } else {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getOrderEntity(final String dealNo, String orderId, final List<ShoppingCarsEntity> shoppingCarsEntity) {
        if (orderId != null) {
            AVQuery<OrderEntity> shoppingCars = new AVQuery<>("order");
            shoppingCars.whereEqualTo("objectId", orderId);
            shoppingCars.findInBackground(new FindCallback<OrderEntity>() {
                @Override
                public void done(List<OrderEntity> list, AVException e) {
                    if (e == null) {
                        if (list.size() != 0) {
                            orderEntity = list.get(0);
                            removeCar(dealNo, shoppingCarsEntity, orderEntity);
                        }
                    } else {
                        e.printStackTrace();
                        mView.showError(e.getMessage());
                    }
                }
            });
        }
    }

    /**
     * @param
     * @param goods
     * @param orderEntity
     */
    @Override
    public void removeCar(final String deal, final List<ShoppingCarsEntity> goods, final OrderEntity orderEntity) {//购物车插进orderId,
        if (goods.size() != 0) {
            AVQuery<ShoppingCarsEntity> query = new AVQuery<>("ShoppingCars");
            query.findInBackground(new FindCallback<ShoppingCarsEntity>() {
                @Override
                public void done(List<ShoppingCarsEntity> list, AVException e) {
                    for (ShoppingCarsEntity entitySon : goods) {
                        String entitySonId = entitySon.getObjectId();
                        for (ShoppingCarsEntity entity : list) {
                            String entityId = entity.getObjectId();
                            if (entitySonId.equals(entityId)) {
                                entity.put("orderId", orderEntity);
                                entity.put("dealOrderId", deal);
                                break;
                            }
                        }
                    }
                    AVObject.saveAllInBackground(list, new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e != null) {
                                mView.showError(e.getMessage());
                            } else {
                                // 保存成功
                            }
                        }
                    });
                }
            });

        }
    }

    AVQuery<Ticket> ticketAVQuery = new AVQuery<>("ticket_discount");
    UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
    String currentUserId = user.getObjectId();


    List<Ticket> ticketList = new ArrayList<>();

    /**
     * 获取可使用的优惠券
     */
    @Override
    public void getFitTicketList(final Float money) {
        mView.showProgress();
        ticketAVQuery.whereEqualTo("user_id", currentUserId);
        ticketAVQuery.findInBackground(new FindCallback<Ticket>() {
            @Override
            public void done(List<Ticket> list, AVException e) {
                if (e == null) {
                    for (Ticket ticket : list) {
                        Float rest = money - Float.parseFloat(ticket.getCondition());
                        if (rest > 0 && ticket.getHadUse().equals("0")) {
                            ticketList.add(ticket);
                        }
                    }
                    mView.getTicket(ticketList);
                } else {
                    e.printStackTrace();
                }
                mView.dismissProgress();
            }
        });
    }

    /**
     * 选择使用优惠券
     */
    @Override
    public void bingTicket(String ticketId) {
        AVObject avObject = AVObject.createWithoutData("ticket_discount", ticketId);
        avObject.put("had_use", orderEntity.getDealOrderId());
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
            }
        });
    }
}
